package tsli.acm.ctrl;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

import javazoom.upload.MultipartFormDataRequest;
import javazoom.upload.UploadBean;
import javazoom.upload.UploadException;
import javazoom.upload.UploadFile;
import tsli.acm.dao.SFCAgentStructureDAO;
import tsli.acm.database.Database;
import tsli.acm.model.SFCAgentStructure;
import tsli.acm.util.Excel;

/**
 * Servlet implementation class ACM2101Srvl
 */
public class ACM2201Srvl extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private Database db;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ACM2201Srvl() {
		super();
		// TODO Auto-generated constructor stub
	}

	public void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// get site_id

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");

		String vaProcessType = request.getParameter("process_type");
		
		if (request.getParameter("process_type").equals("getDataTable")) {
			getDataTable(request, response);
		}else if (request.getParameter("process_type").equals("updateData")) {
			updateDataTable(request, response);
		}else if (request.getParameter("process_type").equals("deleteData")) {
			deleteDataTable(request, response);
		}
		
	}
	
	
	public void getDataTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
    	
    	int vnStart = Integer.parseInt(request.getParameter("iDisplayStart")); // 0
    	int vnAmount = Integer.parseInt(request.getParameter("iDisplayLength")); // 10
    	String vaDraw = request.getParameter("sEcho");
    	String vaPeNo = request.getParameter("sSearch_0").trim();
    	String vaMonth = request.getParameter("sSearch_1").trim();
    	String vaYear = request.getParameter("sSearch_2").trim();

    	// get data from database
    	int vnTotal = 0;
    	int vnTotalAfterFilter = 0;
    	List<Map<String, String>> voResult =  new ArrayList<Map<String, String>>();


    	Database db = new Database();
    	SFCAgentStructureDAO voSFCAgentStructure = new SFCAgentStructureDAO(db);
    	List<Map<String, Object>> vaVPInfo = voSFCAgentStructure.getSFCAgentData(vaPeNo, vaYear+""+vaMonth);
    	
    	try {
    		if(vaVPInfo!=null){
    			vnTotal = vaVPInfo.size();
        		if (vnAmount == -1) {
        			for (int i = 0; i < vaVPInfo.size(); i++) {

        				Map<String, String> voTmp = new HashMap<String, String>();
        				voTmp.put("PE_NO", vaVPInfo.get(i).get("PE_NO").toString());
        				voTmp.put("CLOS_YM", vaVPInfo.get(i).get("CLOS_YM").toString());
        				voTmp.put("TITLE_NAME", vaVPInfo.get(i).get("NM_TITLE_THAI").toString());
        				voTmp.put("NAME", vaVPInfo.get(i).get("NM_THAI").toString());
        				voTmp.put("SURNAME", vaVPInfo.get(i).get("SURNM_THAI").toString());
        				voTmp.put("FST_ENCO_MMS", vaVPInfo.get(i).get("FST_ENCO_MMS").toString());
        				voTmp.put("DTY_CD", vaVPInfo.get(i).get("DTY_CD").toString());
        				voResult.add(voTmp);
        			}
        		    vnTotalAfterFilter = vnTotal;
        		} else {
        			if (vaVPInfo.size() != 0) {
        				for (int i = vnStart; i < (vnStart + vnAmount); i++) {

        					Map<String, String> voTmp = new HashMap<String, String>();
        					voTmp.put("PE_NO", vaVPInfo.get(i).get("PE_NO").toString());
            				voTmp.put("CLOS_YM", vaVPInfo.get(i).get("CLOS_YM").toString());
            				voTmp.put("TITLE_NAME", vaVPInfo.get(i).get("NM_TITLE_THAI").toString());
            				voTmp.put("NAME", vaVPInfo.get(i).get("NM_THAI").toString());
            				voTmp.put("SURNAME", vaVPInfo.get(i).get("SURNM_THAI").toString());
            				voTmp.put("FST_ENCO_MMS", vaVPInfo.get(i).get("FST_ENCO_MMS").toString());
            				voTmp.put("DTY_CD", vaVPInfo.get(i).get("DTY_CD").toString());
        					voResult.add(voTmp);
        					if (i == (vaVPInfo.size() - 1)) 
        						break;
        				}
        			}
        			vnTotalAfterFilter = vnTotal;
        		}
    		}
    	   	
    	} finally {
    		db.close();
    	}  
    	// prepare data to show in dataTable
    	PrintWriter voOut = response.getWriter();
    	// set sequence
    	int[] vnSequence = new int[voResult.size()];
    	for (int i = 1; i <= voResult.size(); i++)
    		vnSequence[i - 1] = i + vnStart;
    	try {
    	   	JSONObject voObject = new JSONObject();
    	    JSONArray voListData = new JSONArray();
    	    for (int i = 0; i < voResult.size(); i++) {
    	    	Map<String, String> voTmp = voResult.get(i);	
    			JSONArray voArray = new JSONArray();
    			voArray.add(vnSequence[i]);
    			voArray.add(voTmp.get("PE_NO"));
    			voArray.add(voTmp.get("CLOS_YM"));
    			voArray.add((voTmp.get("TITLE_NAME") + " " + voTmp.get("NAME") + " " + voTmp.get("SURNAME")));
    			voArray.add(voTmp.get("FST_ENCO_MMS"));
    			voArray.add(voTmp.get("DTY_CD"));
    		    // data for button's action
    			String paName = (voTmp.get("TITLE_NAME") + "," + voTmp.get("NAME") + "," + voTmp.get("SURNAME"));
    			String paData = voTmp.get("PE_NO").toString()+","+paName+","+voTmp.get("CLOS_YM");

    			voArray.add(paData);
    			// adding array data into list
    		    voListData.add(voArray);
    		}
    		voObject.put("sEcho", Integer.parseInt(vaDraw));
    		voObject.put("iTotalRecords", vnTotal);
    		voObject.put("iTotalDisplayRecords", vnTotalAfterFilter);
    		voObject.put("aaData", voListData);
    		voOut.print(voObject.toJSONString());
    	} finally {
    			voOut.close();
    	}
    }
	
	public void updateDataTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		
		
		JSONObject voObject = new JSONObject();
		PrintWriter out = response.getWriter();
		

		try {
			this.db = new Database();
			SFCAgentStructure voSFCAgentStructure = new SFCAgentStructure();
			voSFCAgentStructure.setVaNmTitleThai(request.getParameter("titleNm").trim());
			 voSFCAgentStructure.setVaNmThai(request.getParameter("name").trim());
			 voSFCAgentStructure.setVaSurnmThai(request.getParameter("surNm").trim());
			 voSFCAgentStructure.setVnPeNo(request.getParameter("peNo").trim());
			 voSFCAgentStructure.setVaClosYm(request.getParameter("closYm").trim());
			 
			 
			 SFCAgentStructureDAO voSFCAgentStructureDAO = new SFCAgentStructureDAO(db);
			 
			 voObject.put("result", voSFCAgentStructureDAO.updateSFCAgentData(voSFCAgentStructure));

			out.print(voObject.toJSONString());
			 
			
		} catch (Exception e) {
			e.printStackTrace();
			voObject.put("result", "fail");
			
			out.print(voObject.toJSONString());
		} finally{
			out.close();
			db.close();
		}
	}
	
	public void deleteDataTable(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/JSON");
		
		String vaPeNo = request.getParameter("peNo").trim();
		String vaClosYm = request.getParameter("closYm").trim();
		
		Database db = new Database();
		JSONObject voObject = new JSONObject();
		PrintWriter out = response.getWriter();
		
		try {
			SFCAgentStructureDAO voSFCAgentStructureDAO = new SFCAgentStructureDAO(db);
			 
			voObject.put("result", voSFCAgentStructureDAO.deleteSFCAgentData(vaPeNo,vaClosYm));
				
			out.print(voObject.toJSONString());
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			out.close();
			db.close();
		}
	}

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

}
